package com.xoms.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xoms.admin.cache.dao.ResourceCache;
import com.xoms.admin.controller.res.bean.RHaveResourcesBean;
import com.xoms.admin.controller.res.bean.RResourceBean;
import com.xoms.admin.model.AccountBean;
import com.xoms.admin.model.ResourceBean;
import com.xoms.admin.model.vo.HaveResourcesBean;
import com.xoms.admin.model.vo.RoleResourceBean;
import com.xoms.admin.persist.dao.ResourceDao;
import com.xoms.admin.persist.dao.RoleDao;
import com.xoms.admin.service.ResourceService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.DateTimeUtil;

@Service
public class ResourceServiceImpl implements ResourceService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	ResourceDao resourceImpl;
	
	@Autowired
	RoleDao roleImpl;

	@Autowired
	ResourceCache resourceCacheImpl;

	@Override
	public PageResult<RHaveResourcesBean> getAccountResources(AccountBean account, String accId) {
		PageResult<RHaveResourcesBean> result = new PageResult<RHaveResourcesBean>();
		List<RHaveResourcesBean> resList = new ArrayList<RHaveResourcesBean>();
		// 从缓存中获取 用户权限
		List<HaveResourcesBean> resources = resourceCacheImpl.getAccountResource(accId);
		if(null == resources || resources.isEmpty()) {// 缓存内无账号权限列表，查询账号角色
			// 获取账号角色id列表，从缓存获取角色对应权限，去重
			List<RoleResourceBean> roles = roleImpl.selectRoleResouces2Account(accId);
			logger.info("account roles is" + JSON.toJSONString(roles));
			if(roles != null && !roles.isEmpty()) {
				resources = resourceCacheImpl.setAccountResource(accId, roles);
			}
		}
		if(resources != null && !resources.isEmpty()) {
			// 循环赋值
			for(HaveResourcesBean resource : resources) {
				resList.add(parse(resource));
			}
		}
		result.setData(resList);
		result.setCount(resList.size());
		return result;
	}

	@Override
	public RResourceBean edit(AccountBean account, int rid, String name, int parentId, String url, int type, int level,
			int isEnable, String resDesc, int sort) {
		ResourceBean data = new ResourceBean();
		boolean flag = false;
		data.setName(name);
		data.setPid(parentId);
		data.setStatus(isEnable);
		data.setUrl(url);
		data.setPid(parentId);
		data.setType(type);
		data.setLevel(level);
		data.setRemark(resDesc);
		data.setSort(sort);

		if (rid == -1) {// 新建
	
			data.setAccountId(account.getAccid());
			flag = resourceImpl.insert(data) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","权限信息");
			}
		} else {
			data.setRid(rid);
			flag = resourceImpl.update(data) > 0;// 更新数据库
			if (!flag) {
				throw new ServiceException("database_update_fail","权限信息");
			}
		}
		
		resourceCacheImpl.clearAllAccountResource();
		resourceCacheImpl.clearAllRoleResource();
		return parseResource(resourceImpl.selectOneById(data.getRid()));
	}

	@Override
	public boolean enable(AccountBean account, int rid) {
		if (resourceImpl.updateStatus(rid, 1) > 0) {// 更新状态
			System.out.println(123123123);
			resourceCacheImpl.clearAllAccountResource();
			resourceCacheImpl.clearAllRoleResource();
			return true;
		}

		return false;
	}

	@Override
	public boolean disable(AccountBean account, int rid) {
		if (resourceImpl.updateStatus(rid, 0) > 0) {// 更新状态
			System.out.println(13123);
			resourceCacheImpl.clearAllAccountResource();
			resourceCacheImpl.clearAllRoleResource();
			return true;
		}

		return false;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean del(AccountBean account, int rid) {
		boolean flag = false;
		// 删除权限前判断：1有无角色关联该权限
		int roleNum = resourceImpl.selectRoleNum2Resource(rid);
		if(roleNum > 0) {
			// 删除关联关系
			flag = resourceImpl.delAllResourceRelation(rid) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","权限关系");
			}
		}
		flag = resourceImpl.del(rid) > 0;
		if(!flag) {
			throw new ServiceException("database_delete_fail","权限信息");
		}
		resourceCacheImpl.clearAllRoleResource();
		return flag;
	}

	@Override
	public PageResult<RResourceBean> getResources(AccountBean account, String key, int page, int pagesize) {
		PageResult<RResourceBean> result = new PageResult<RResourceBean>();
		List<RResourceBean> resList = new ArrayList<RResourceBean>();
		// 获取权限数量
		int count = resourceImpl.selectCount(key);
		if (count > 0) {
			// 数量不为0时获取权限列表
			List<ResourceBean> lists = resourceImpl.selectList(key, page, pagesize);

			if (lists != null) {
				RResourceBean rr = null;
				for (ResourceBean res : lists) {
					rr = new RResourceBean();
					rr = parseResource(res);
					resList.add(rr);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}
	/**
	 * 格式化数据
	 * @param res
	 * @return
	 */
	private RResourceBean parseResource(ResourceBean res) {
		RResourceBean rr = new RResourceBean();
		rr.setId(res.getRid());
		rr.setName(res.getName());
		rr.setPid(res.getPid());
		rr.setLevel(res.getLevel());
		rr.setResDesc(res.getRemark());
		rr.setType(res.getType());
		rr.setUrl(res.getUrl());
		rr.setIsEnable(res.getStatus());
		rr.setCreateTime(DateTimeUtil.formatTimestamp(res.getCreateTime()));
		rr.setUpdateTime(DateTimeUtil.formatTimestamp(res.getUpdateTime()));
		return rr;
	}

	@Override
	public PageResult<RHaveResourcesBean> getRoleResources(AccountBean account, int roleId) {
		PageResult<RHaveResourcesBean> result = new PageResult<RHaveResourcesBean>();
		List<RHaveResourcesBean> resList = new ArrayList<RHaveResourcesBean>();
		// 从缓存中获取 角色权限
		List<HaveResourcesBean> resources = resourceCacheImpl.getRoleResource(roleId);
		if(null == resources || resources.isEmpty()) {// 缓存内无角色权限列表，从数据库查询
			// 根据id获取权限列表
			resources = resourceImpl.selectResources2Role(roleId);
			resourceCacheImpl.setRoleResource(roleId, resources);
		}
		if(resources != null && !resources.isEmpty()) {
			// 循环赋值
			for(HaveResourcesBean resource : resources) {
				resList.add(parse(resource));
			}
		}
		result.setData(resList);
		result.setCount(resList.size());
		return result;
	}
	

	/**
	 * 格式化数据
	 * @param selectOneById
	 * @return
	 */
	private RHaveResourcesBean parse(HaveResourcesBean resource) {
		RHaveResourcesBean rh = new RHaveResourcesBean();
		rh.setLevel(resource.getLevel());
		rh.setPid(resource.getPid());
		rh.setResourceName(resource.getResourceName());
		rh.setRid(resource.getRid());
		rh.setType(resource.getType());
		rh.setUrl(resource.getUrl());
		return rh;
	}

	@Override
	public boolean editSorts2Resource(String sorts, int page, int pagesize) {
		boolean flag = false;
		List<String> sortList = JSON.parseArray(sorts, String.class);
		flag = resourceImpl.updateSorts(sortList, page, pagesize) > 0;
		resourceCacheImpl.clearAllAccountResource();
		resourceCacheImpl.clearAllRoleResource();
		return flag;
	}
	
	
	
}
